<?php

$di = \application\units\Di::getInstance();

$params = [
    'admin_id' => $di->auth->id,
    'field'    => $di->request->params('field'),
    'value'    => $di->request->params('value'),
    'id'       => explode(',', (string)$di->request->params('id')),
];

if ($params['admin_id']) {
    $adminIds    = $di->auth->getChildrenRoleAdminIds($params['admin_id'], true);
    $authRoleIds = $di->auth->getRoleIdsByAdminId($params['admin_id']);
} else {
    $adminIds = [$params['admin_id']];
}


$roles = $di->db->query('select a.admin_id,g.* from admin_role_access a
            join admin_role g on g.id=a.role_id
            where admin_id in (:admin_id)', [
    'admin_id' => $params['id'],
]);

foreach ($roles as $adminId => $role) {
    // 不能操作自己拥有的权限
    if (array_intersect(array_column($role, 'id'), $authRoleIds)) {
        throw new LogicException('不能删除跟自己相同角色的管理员');
    }
}

$params['id'] = array_intersect($params['id'], $adminIds);

$row = $di->db->find('select * from admin where id in (:id)', [
    'id' => $params['id'],
]);

if (!$row) throw new LogicException('未找到记录');

if (!isset($row[$params['field']])) throw new LogicException('操作字段不存在');

$stat = $di->db->execute(sprintf('update admin set %s=:value where id in (:id)', $params['field']), [
    'value' => $params['value'],
    'id'    => $params['id'],
]);

if ($stat->rowCount() <= 0) throw new PDOException('操作失败');

return [];